"use client";

import { useState, useEffect, useRef } from "react";
import { motion } from "framer-motion";
import {
  FiPlus,
  FiEdit2,
  FiTrash2,
  FiX,
  FiCheck,
  FiSearch,
  FiChevronDown,
  FiFilter,
} from "react-icons/fi";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";

// 模拟标签数据
const mockTags = [
  { id: "1", name: "架构", color: "#3B82F6", category: "技术" },
  { id: "2", name: "设计", color: "#8B5CF6", category: "技术" },
  { id: "3", name: "需求", color: "#10B981", category: "产品" },
  { id: "4", name: "产品", color: "#F59E0B", category: "产品" },
  { id: "5", name: "财务", color: "#EF4444", category: "业务" },
  { id: "6", name: "报告", color: "#EC4899", category: "业务" },
  { id: "7", name: "培训", color: "#6366F1", category: "人力资源" },
  { id: "8", name: "HR", color: "#14B8A6", category: "人力资源" },
  { id: "9", name: "市场", color: "#F97316", category: "营销" },
  { id: "10", name: "营销", color: "#84CC16", category: "营销" },
];

// 标签类别
const categories = [
  { id: "all", name: "全部类别" },
  { id: "tech", name: "技术" },
  { id: "product", name: "产品" },
  { id: "business", name: "业务" },
  { id: "hr", name: "人力资源" },
  { id: "marketing", name: "营销" },
];

// 预定义的颜色选项
const colorOptions = [
  "#3B82F6", // 蓝色
  "#8B5CF6", // 紫色
  "#10B981", // 绿色
  "#F59E0B", // 橙色
  "#EF4444", // 红色
  "#EC4899", // 粉色
  "#6366F1", // 靛蓝色
  "#14B8A6", // 青色
  "#F97316", // 橙红色
  "#84CC16", // 黄绿色
  "#0EA5E9", // 天蓝色
  "#7C3AED", // 深紫色
];

export default function TagsManagementPage() {
  const [tags, setTags] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [showCategoryDropdown, setShowCategoryDropdown] = useState(false);
  const categoryDropdownRef = useRef(null);

  // 标签编辑状态
  const [editingTag, setEditingTag] = useState(null);
  const [tagForm, setTagForm] = useState({
    name: "",
    color: "#3B82F6",
    category: "技术",
  });

  // 创建标签弹窗状态
  const [isCreatingTag, setIsCreatingTag] = useState(false);
  const [showCategoryInput, setShowCategoryInput] = useState(false);
  const [newCategory, setNewCategory] = useState("");

  // 关闭下拉菜单的点击外部处理函数
  useEffect(() => {
    function handleClickOutside(event) {
      if (
        categoryDropdownRef.current &&
        !categoryDropdownRef.current.contains(event.target)
      ) {
        setShowCategoryDropdown(false);
      }
    }

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  useEffect(() => {
    // 模拟API获取标签列表
    const fetchTags = async () => {
      try {
        // 模拟延迟
        await new Promise((resolve) => setTimeout(resolve, 600));

        // 使用模拟数据
        setTags(mockTags);
      } catch (error) {
        console.error("获取标签列表失败:", error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchTags();
  }, []);

  // 筛选标签
  const filteredTags = tags.filter((tag) => {
    const matchesSearch = tag.name
      .toLowerCase()
      .includes(searchQuery.toLowerCase());
    const matchesCategory =
      selectedCategory === "all" ||
      tag.category === categories.find((c) => c.id === selectedCategory)?.name;

    return matchesSearch && matchesCategory;
  });

  const handleCreateTag = () => {
    setTagForm({ name: "", color: colorOptions[0], category: "技术" });
    setIsCreatingTag(true);
  };

  const handleSaveNewTag = () => {
    // 表单验证
    if (!tagForm.name.trim()) {
      alert("标签名称不能为空");
      return;
    }

    const newTag = {
      id: (tags.length + 1).toString(),
      name: tagForm.name.trim(),
      color: tagForm.color,
      category:
        showCategoryInput && newCategory
          ? newCategory.trim()
          : tagForm.category,
    };

    setTags([...tags, newTag]);
    setIsCreatingTag(false);
    setShowCategoryInput(false);
    setNewCategory("");
  };

  const handleEditTag = (tag) => {
    setEditingTag(tag.id);
    setTagForm({
      name: tag.name,
      color: tag.color,
      category: tag.category,
    });
    setShowCategoryInput(false);
  };

  const handleUpdateTag = (id) => {
    // 表单验证
    if (!tagForm.name.trim()) {
      alert("标签名称不能为空");
      return;
    }

    const updatedTags = tags.map((tag) =>
      tag.id === id
        ? {
            ...tag,
            name: tagForm.name.trim(),
            color: tagForm.color,
            category:
              showCategoryInput && newCategory
                ? newCategory.trim()
                : tagForm.category,
          }
        : tag
    );

    setTags(updatedTags);
    setEditingTag(null);
    setShowCategoryInput(false);
    setNewCategory("");
  };

  const handleDeleteTag = (id) => {
    if (window.confirm("确定要删除这个标签吗？此操作不可撤销。")) {
      const updatedTags = tags.filter((tag) => tag.id !== id);
      setTags(updatedTags);
    }
  };

  const fadeIn = {
    hidden: { opacity: 0, y: 20 },
    visible: { opacity: 1, y: 0 },
  };

  if (isLoading) {
    return (
      <div className='flex justify-center items-center h-[80vh]'>
        <div className='animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-blue-500'></div>
      </div>
    );
  }

  return (
    <div className='container mx-auto px-4 py-8'>
      <motion.div
        initial='hidden'
        animate='visible'
        variants={fadeIn}
        transition={{ duration: 0.3 }}
      >
        {/* 页面标题和操作区 */}
        <div className='flex justify-between items-center mb-8'>
          <h1 className='text-3xl font-bold text-gray-800 dark:text-white'>
            标签管理
          </h1>
          <Button
            onClick={handleCreateTag}
            className='bg-blue-500 hover:bg-blue-600 text-white'
          >
            <FiPlus className='mr-2' /> 新建标签
          </Button>
        </div>

        {/* 搜索和筛选区 */}
        <div className='bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-4 mb-6'>
          <div className='flex flex-col md:flex-row gap-4'>
            <div className='relative flex-1'>
              <div className='absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none'>
                <FiSearch className='text-gray-400' />
              </div>
              <Input
                type='text'
                placeholder='搜索标签...'
                className='pl-10'
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
              />
            </div>

            {/* 类别选择器 */}
            <div className='w-full md:w-64 relative' ref={categoryDropdownRef}>
              <button
                className='w-full flex items-center justify-between px-3 py-2 text-sm border rounded-md shadow-sm bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-600'
                onClick={() => setShowCategoryDropdown(!showCategoryDropdown)}
              >
                <div className='flex items-center'>
                  <FiFilter className='mr-2' />
                  <span>
                    {categories.find((c) => c.id === selectedCategory)?.name ||
                      "选择类别"}
                  </span>
                </div>
                <FiChevronDown
                  className={`transition-transform ${
                    showCategoryDropdown ? "rotate-180" : ""
                  }`}
                />
              </button>

              {showCategoryDropdown && (
                <div className='absolute z-10 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md shadow-lg'>
                  <ul className='py-1'>
                    {categories.map((category) => (
                      <li
                        key={category.id}
                        className={`px-3 py-2 text-sm cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 ${
                          selectedCategory === category.id
                            ? "bg-gray-100 dark:bg-gray-700 font-medium"
                            : ""
                        }`}
                        onClick={() => {
                          setSelectedCategory(category.id);
                          setShowCategoryDropdown(false);
                        }}
                      >
                        {category.name}
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* 标签列表 */}
        <div className='bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden mb-8'>
          <table className='w-full'>
            <thead className='bg-gray-50 dark:bg-gray-700'>
              <tr>
                <th className='px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider'>
                  标签名称
                </th>
                <th className='px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider'>
                  颜色
                </th>
                <th className='px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider'>
                  类别
                </th>
                <th className='px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider'>
                  操作
                </th>
              </tr>
            </thead>
            <tbody className='divide-y divide-gray-200 dark:divide-gray-700'>
              {filteredTags.map((tag) => (
                <tr
                  key={tag.id}
                  className='hover:bg-gray-50 dark:hover:bg-gray-700/30'
                >
                  <td className='px-6 py-4'>
                    {editingTag === tag.id ? (
                      <Input
                        type='text'
                        value={tagForm.name}
                        onChange={(e) =>
                          setTagForm({ ...tagForm, name: e.target.value })
                        }
                        className='w-full'
                      />
                    ) : (
                      <div className='flex items-center'>
                        <span
                          className='w-3 h-3 rounded-full mr-3'
                          style={{ backgroundColor: tag.color }}
                        ></span>
                        <span className='font-medium text-gray-900 dark:text-white'>
                          {tag.name}
                        </span>
                      </div>
                    )}
                  </td>
                  <td className='px-6 py-4'>
                    {editingTag === tag.id ? (
                      <div className='flex flex-wrap gap-2'>
                        {colorOptions.map((color) => (
                          <button
                            key={color}
                            type='button'
                            className={`w-6 h-6 rounded-full border-2 ${
                              tagForm.color === color
                                ? "border-gray-800 dark:border-white"
                                : "border-transparent"
                            }`}
                            style={{ backgroundColor: color }}
                            onClick={() => setTagForm({ ...tagForm, color })}
                          ></button>
                        ))}
                      </div>
                    ) : (
                      <div className='flex items-center'>
                        <span
                          className='w-6 h-6 rounded-full'
                          style={{ backgroundColor: tag.color }}
                        ></span>
                      </div>
                    )}
                  </td>
                  <td className='px-6 py-4'>
                    {editingTag === tag.id ? (
                      showCategoryInput ? (
                        <Input
                          type='text'
                          value={newCategory}
                          onChange={(e) => setNewCategory(e.target.value)}
                          placeholder='输入新类别'
                          className='w-full'
                        />
                      ) : (
                        <div className='flex items-center'>
                          <select
                            value={tagForm.category}
                            onChange={(e) =>
                              setTagForm({
                                ...tagForm,
                                category: e.target.value,
                              })
                            }
                            className='w-full rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 px-3 py-2 text-sm'
                          >
                            {categories
                              .filter((c) => c.id !== "all")
                              .map((category) => (
                                <option key={category.id} value={category.name}>
                                  {category.name}
                                </option>
                              ))}
                          </select>
                          <Button
                            variant='ghost'
                            size='sm'
                            onClick={() => setShowCategoryInput(true)}
                            className='ml-2'
                          >
                            <FiPlus />
                          </Button>
                        </div>
                      )
                    ) : (
                      <span className='text-gray-700 dark:text-gray-300'>
                        {tag.category}
                      </span>
                    )}
                  </td>
                  <td className='px-6 py-4 whitespace-nowrap text-right text-sm font-medium'>
                    {editingTag === tag.id ? (
                      <div className='flex justify-end space-x-2'>
                        <Button
                          variant='outline'
                          size='sm'
                          onClick={() => {
                            setEditingTag(null);
                            setShowCategoryInput(false);
                          }}
                        >
                          <FiX className='mr-1' /> 取消
                        </Button>
                        <Button
                          variant='default'
                          size='sm'
                          onClick={() => handleUpdateTag(tag.id)}
                          className='bg-green-500 hover:bg-green-600 text-white'
                        >
                          <FiCheck className='mr-1' /> 保存
                        </Button>
                      </div>
                    ) : (
                      <div className='flex justify-end space-x-2'>
                        <Button
                          variant='ghost'
                          size='sm'
                          onClick={() => handleEditTag(tag)}
                          className='text-blue-500 hover:text-blue-700'
                        >
                          <FiEdit2 />
                        </Button>
                        <Button
                          variant='ghost'
                          size='sm'
                          onClick={() => handleDeleteTag(tag.id)}
                          className='text-red-500 hover:text-red-700'
                        >
                          <FiTrash2 />
                        </Button>
                      </div>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* 新建标签弹窗 */}
        {isCreatingTag && (
          <div className='fixed inset-0 bg-black/50 bg-opacity-30 backdrop-blur-sm flex justify-center items-center p-4 z-50'>
            <div className='bg-white dark:bg-gray-800 rounded-lg shadow-lg max-w-md w-full p-6'>
              <h3 className='text-xl font-semibold mb-4 text-gray-800 dark:text-white'>
                新建标签
              </h3>

              <div className='space-y-4'>
                <div>
                  <label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1'>
                    标签名称
                  </label>
                  <Input
                    type='text'
                    value={tagForm.name}
                    onChange={(e) =>
                      setTagForm({ ...tagForm, name: e.target.value })
                    }
                    placeholder='输入标签名称'
                    className='w-full'
                  />
                </div>

                <div>
                  <label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1'>
                    标签颜色
                  </label>
                  <div className='flex flex-wrap gap-2'>
                    {colorOptions.map((color) => (
                      <button
                        key={color}
                        type='button'
                        className={`w-8 h-8 rounded-full border-2 ${
                          tagForm.color === color
                            ? "border-gray-800 dark:border-white"
                            : "border-transparent"
                        }`}
                        style={{ backgroundColor: color }}
                        onClick={() => setTagForm({ ...tagForm, color })}
                      ></button>
                    ))}
                  </div>
                </div>

                <div>
                  <label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1'>
                    标签类别
                  </label>
                  {showCategoryInput ? (
                    <div className='flex'>
                      <Input
                        type='text'
                        value={newCategory}
                        onChange={(e) => setNewCategory(e.target.value)}
                        placeholder='输入新类别'
                        className='w-full'
                      />
                      <Button
                        variant='ghost'
                        size='sm'
                        onClick={() => setShowCategoryInput(false)}
                        className='ml-2'
                      >
                        <FiX />
                      </Button>
                    </div>
                  ) : (
                    <div className='flex'>
                      <select
                        value={tagForm.category}
                        onChange={(e) =>
                          setTagForm({ ...tagForm, category: e.target.value })
                        }
                        className='w-full rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 px-3 py-2 text-sm'
                      >
                        {categories
                          .filter((c) => c.id !== "all")
                          .map((category) => (
                            <option key={category.id} value={category.name}>
                              {category.name}
                            </option>
                          ))}
                      </select>
                      <Button
                        variant='ghost'
                        size='sm'
                        onClick={() => setShowCategoryInput(true)}
                        className='ml-2'
                      >
                        <FiPlus />
                      </Button>
                    </div>
                  )}
                </div>
              </div>

              <div className='flex justify-end mt-6 space-x-3'>
                <Button
                  variant='outline'
                  onClick={() => {
                    setIsCreatingTag(false);
                    setShowCategoryInput(false);
                  }}
                >
                  取消
                </Button>
                <Button
                  onClick={handleSaveNewTag}
                  className='bg-blue-500 hover:bg-blue-600 text-white'
                >
                  创建标签
                </Button>
              </div>
            </div>
          </div>
        )}
      </motion.div>
    </div>
  );
}
